﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Xyz.Web.Reservation.Models;
using Xyz.Web.Reservation.Repositories;

namespace Xyz.Web.Reservation.Controllers
{
    public class BookingController : Controller
    {
        //
        // GET: /Booking/

        [HttpGet]
        public ActionResult Booking(string bookingCode)
        {
            //if (booking == null)
            //{
            //    if (TempData["BookingModel"] != null)
            //    {
            //        booking = (BookingModel) TempData["BookingModel"];
            //    }
            //    else
            //    {
            //        throw new ApplicationException("An error occured on: ActionResult Booking(BookingModel booking)");
            //    }
            //}

            var booking = GetBooking(bookingCode);

            //TODO: Populate the booking session
            Session["booking"] = booking;

            return View(booking);
        }

        [HttpGet]
        public ActionResult Search()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Search(FormCollection collection)
        {
            var bookingCode = collection["bookingCode"];
            ViewData["Result"] = "Please enter booking Id";

            if (bookingCode != string.Empty)
            {
                var booking = GetBooking(bookingCode);

                if (booking != null)
                {
                    return RedirectToAction("Booking", "Booking", new { booking.BookingCode });
                }

                ViewData["Result"] = "Booking code does not exist.";
            }

            return View();
        }

        public ActionResult Bookings(int customerId)
        {
            List<BookingModel> bookings = BookingRepository.GetCustomerBookings(customerId).ToModel();

            return View(bookings);
        }


        public ActionResult CancelBooking()
        {
            var bookingModel = ((BookingModel)Session["booking"]);

            BookingRepository.CancelBooking(bookingModel.BookingId);

            return View();
        }

        private static BookingModel GetBooking(string bookingCode)
        {
            return BookingRepository.GetBooking(bookingCode).ToModel();
        }
    }
}
